// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.gui;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import net.web2me.api.CommonConstants;
import net.web2me.api.ParserExecutor;

import org.apache.log4j.Logger;

public class GuiParserExecutorWrapper {
	
	private Logger logger = Logger.getLogger(GuiParserExecutorWrapper.class);
	
	private JPanel context;
	
	private ParserExecutor executor;
	
	private Thread runner;
	
	private JLabel infoLabel;
	
	private GuiParserExecutorWrapperListener listener;

	public GuiParserExecutorWrapper(JPanel context, ParserExecutor executor, GuiParserExecutorWrapperListener listener) {
		this.context = context;
		this.executor = executor;
		this.listener = listener;
		
		infoLabel = (JLabel) context.getComponent(Web2MeGuiSwing.INFO_LABEL);
	}


	public void execute() {
		runner = new Thread(new Runnable() {

			public void run() {
				String result = CommonConstants.EMPTY;
				try {
					result = executor.execute();
				} catch (Throwable t) {
					result = t.getMessage();
					logger.error("Error starting to process", t);
				}
				
				listener.onParserFinished();
				
				JOptionPane.showMessageDialog(context, result);
			}
			
		});
		
		runner.start();
		
		infoLabel.setText("Parser started");
	}
	
	public void abort() {
		runner.interrupt();
		infoLabel.setText("Parser aborted");
	}

}
